/**
 * Copyright 2021 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.module;

import java.util.List;

import com.jianggujin.modulelink.config.JModuleConfig;
import com.jianggujin.modulelink.util.JLogFactory;
import com.jianggujin.modulelink.util.JLogFactory.JLog;

/**
 * 模块事件发布器
 * 
 * @author jianggujin
 *
 */
public class JModuleEventPublisher {

    private static final JLog logger = JLogFactory.getLog(JModuleEventPublisher.class);
    private static volatile JModuleEventPublisher instance;
    /**
     * 模块监听器
     */
    private final List<JModuleListener> listeners;

    public JModuleEventPublisher(List<JModuleListener> listeners) {
        this.listeners = listeners;
    }

    /**
     * 发布模块状态改变事件
     * 
     * @param moduleConfig
     * @param oldModuleState
     * @param newModuleState
     * 
     */
    public void publishStateChangedEvent(final JModuleConfig moduleConfig, final JModuleState oldModuleState,
            final JModuleState newModuleState) {
        if (listeners == null) {
            return;
        }
        for (JModuleListener listener : listeners) {
            try {
                listener.onStateChanged(moduleConfig, oldModuleState, newModuleState);
            } catch (Exception e) {
                logger.error("publish module event has error", e);
            }
        }
    }

    public static JModuleEventPublisher getInstance() {
        if (instance == null) {
            synchronized (JModuleEventPublisher.class) {
                if (instance == null) {
                    instance = new JModuleEventPublisher(null);
                }
            }
        }
        return instance;
    }
}
